﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a layer setting services configure node id transfer
    /// </summary>
    public class LayerSettingServicesConfigureNodeIdTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isMasterTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private LayerSettingServicesConfigureNodeIdMessageReceivedEventHandler _layerSettingServicesConfigureNodeIdMessageReceivedEventHandler;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default send COB-ID
        /// </summary>
        static public readonly UInt16 DefaultMasterCobId = 0x7E5;
        /// <summary>
        /// Default receive COB-ID
        /// </summary>
        static public readonly UInt16 DefaultSlaveCobId = 0x7E4;


        /// <summary>
        /// Initializes a new instance of the
        /// LayerSettingServicesConfigureNodeIdTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="slaveCobId">
        /// Slave COB-ID
        /// </param>
        /// <param name="layerSettingServicesConfigureNodeIdMessageReceivedEventHandler">
        /// Layer setting services configure node id message received event
        /// handler (or null)
        /// </param>
        private LayerSettingServicesConfigureNodeIdTransfer(CanOpenMessage receivedCanOpenMessage, UInt16 slaveCobId, LayerSettingServicesConfigureNodeIdMessageReceivedEventHandler layerSettingServicesConfigureNodeIdMessageReceivedEventHandler)
        {
            _isMasterTransfer = false;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _layerSettingServicesConfigureNodeIdMessageReceivedEventHandler = layerSettingServicesConfigureNodeIdMessageReceivedEventHandler;
            SlaveCobId = slaveCobId;
        }

        /// <summary>
        /// Initializes a new instance of the
        /// LayerSettingServicesConfigureNodeIdTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="newNodeId">
        /// New node id
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public LayerSettingServicesConfigureNodeIdTransfer(byte newNodeId)
            : this(newNodeId, DefaultMasterCobId, DefaultSlaveCobId)
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// LayerSettingServicesConfigureNodeIdTransfer class by the given
        /// parameter
        /// </summary>
        /// <param name="newNodeId">
        /// New node id
        /// </param>
        /// <param name="masterCobId">
        /// Master COB-ID
        /// </param>
        /// <param name="slaveCobId">
        /// Slave COB-ID
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public LayerSettingServicesConfigureNodeIdTransfer(byte newNodeId, UInt16 masterCobId, UInt16 slaveCobId)
        {
            if (!(1 <= newNodeId && newNodeId <= 127))
            {
                throw new ArgumentOutOfRangeException("newNodeId", "The new node id must be in the range of 1..127");
            }
            _isMasterTransfer = true;
            NewNodeId = newNodeId;
            MasterCobId = masterCobId;
            SlaveCobId = slaveCobId;
        }


        /// <summary>
        /// Gets the error code
        /// </summary>
        public byte ErrorCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the implementation specific error code
        /// </summary>
        public byte ImplementationSpecificErrorCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets or sets the new node id
        /// </summary>
        private byte NewNodeId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the master COB-ID
        /// </summary>
        private UInt16 MasterCobId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the slave COB-ID
        /// </summary>
        private UInt16 SlaveCobId
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a layer setting
        /// services configure node id transfer request and if so it returns as
        /// out parameter a matching layer setting services configure node id
        /// transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="layerSettingServicesConfigureNodeIdTransfer">
        /// A matching layer setting services configure node id transfer
        /// instance
        /// </param>
        /// <param name="layerSettingServicesConfigureNodeIdMessageReceivedEventHandler">
        /// Layer setting services configure node id message received event
        /// handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a layer setting services
        /// configure node id transfer request, false otherwise
        /// </returns>
        static public bool IsLayerSettingServicesConfigureNodeIdTransfer(CanOpenMessage receivedCanOpenMessage, out LayerSettingServicesConfigureNodeIdTransfer layerSettingServicesConfigureNodeIdTransfer, LayerSettingServicesConfigureNodeIdMessageReceivedEventHandler layerSettingServicesConfigureNodeIdMessageReceivedEventHandler)
        {
            return IsLayerSettingServicesConfigureNodeIdTransfer(receivedCanOpenMessage, out layerSettingServicesConfigureNodeIdTransfer, DefaultMasterCobId, DefaultSlaveCobId, layerSettingServicesConfigureNodeIdMessageReceivedEventHandler);
        }

        /// <summary>
        /// Checks if the given received can open message is a layer setting
        /// services configure node id transfer request and if so it returns as
        /// out parameter a matching layer setting services configure node id
        /// transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="layerSettingServicesConfigureNodeIdTransfer">
        /// A matching layer setting services configure node id transfer
        /// instance
        /// </param>
        /// <param name="masterCobId">
        /// Master COB-ID
        /// </param>
        /// <param name="slaveCobId">
        /// Slave COB-ID
        /// </param>
        /// <param name="layerSettingServicesConfigureNodeIdMessageReceivedEventHandler">
        /// Layer setting services configure node id message received event
        /// handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a layer setting services
        /// configure node id transfer request, false otherwise
        /// </returns>
        static public bool IsLayerSettingServicesConfigureNodeIdTransfer(CanOpenMessage receivedCanOpenMessage, out LayerSettingServicesConfigureNodeIdTransfer layerSettingServicesConfigureNodeIdTransfer, UInt16 masterCobId, UInt16 slaveCobId, LayerSettingServicesConfigureNodeIdMessageReceivedEventHandler layerSettingServicesConfigureNodeIdMessageReceivedEventHandler)
        {
            // check parameter
            if (receivedCanOpenMessage == null)
            {
                layerSettingServicesConfigureNodeIdTransfer = null;
                return false;
            }

            // check COB-ID
            if (receivedCanOpenMessage.CanId != masterCobId)
            {
                layerSettingServicesConfigureNodeIdTransfer = null;
                return false;
            }

            // check command specifier
            if (receivedCanOpenMessage.Byte0 != (byte)0x11)
            {
                layerSettingServicesConfigureNodeIdTransfer = null;
                return false;
            }

            // create transfer instance
            layerSettingServicesConfigureNodeIdTransfer = new LayerSettingServicesConfigureNodeIdTransfer(receivedCanOpenMessage, slaveCobId, layerSettingServicesConfigureNodeIdMessageReceivedEventHandler);
            return true;
        }

        /// <summary>
        /// Starts the master transfer
        /// </summary>
        private void startMasterTransfer()
        {
            UInt16 canId = MasterCobId;
            byte byte0 = 0x11;
            byte byte1 = NewNodeId;
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, byte1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 8));
            TransferComplete = false;
        }

        /// <summary>
        /// Starts the slave transfer
        /// </summary>
        private void startSlaveTransfer()
        {
            // process data
            byte newNodeId = _receivedCanOpenMessage.Byte0;
            byte errorCode = ((1 <= newNodeId && newNodeId <= 127) ? (byte)0x00 : (byte)0x01);
            byte implementationSpecificErrorCode = 0x00;
            if (_layerSettingServicesConfigureNodeIdMessageReceivedEventHandler != null)
            {
                _layerSettingServicesConfigureNodeIdMessageReceivedEventHandler(this, new LayerSettingServicesConfigureNodeIdMessageReceivedEventArgs(newNodeId, errorCode, implementationSpecificErrorCode));
            }

            // end transfer
            ErrorCode = errorCode;
            ImplementationSpecificErrorCode = implementationSpecificErrorCode;
            _pendingSendMessages.Clear();
            _pendingSendMessages.Add(new CanOpenMessage(SlaveCobId, 0x11, errorCode, implementationSpecificErrorCode, 0x00, 0x00, 0x00, 0x00, 0x00, 8));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Processes the received message for a master transfer
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        private bool processReceivedMessageForMasterTransfer(CanOpenMessage receivedCanOpenMessage)
        {
            // check cob-id
            if (receivedCanOpenMessage.CanId != SlaveCobId)
            {
                return false;
            }

            // check command specifier
            if (receivedCanOpenMessage.Byte0 != (byte)0x11)
            {
                return false;
            }

            // close transfer
            ErrorCode = receivedCanOpenMessage.Byte1;
            ImplementationSpecificErrorCode = receivedCanOpenMessage.Byte2;
            _pendingSendMessages.Clear();
            TransferComplete = true;
            return true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isMasterTransfer)
            {
                startMasterTransfer();
            }
            else
            {
                startSlaveTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            if (_isMasterTransfer)
            {
                return processReceivedMessageForMasterTransfer(receivedCanOpenMessage);
            }
            return false;
        }
        #endregion ITransfer implementation

    }

}
